// pages/question-bank/question-bank.js
const app = getApp()

Page({
  // 难度等级映射
  getDifficultyClass(difficulty) {
    const difficultyMap = {
      '简单': 'easy',
      '中等': 'medium', 
      '困难': 'hard',
      'easy': 'easy',
      'medium': 'medium',
      'hard': 'hard'
    }
    return difficultyMap[difficulty] || 'medium'
  },
  data: {
    searchValue: '',
    questionList: [],
    filteredQuestions: [],
    categories: ['全部', '前端开发', '后端开发', '数据库', '算法'],
    selectedCategory: '全部',
    // 搜索相关
    isSearching: false,
    showSearchResult: false,
    searchHistory: [],
    hotSearches: ['JavaScript', 'Vue.js', 'React', 'Node.js', 'MySQL', '算法', 'CSS', 'HTML'],
    searchDebounceTimer: null
  },

  onLoad() {
    this.setData({
      questionList: app.globalData.questionBanks,
      filteredQuestions: app.globalData.questionBanks
    })
    this.loadSearchHistory()
  },

  onShow() {
    this.loadSearchHistory()
  },

  // 加载搜索历史
  loadSearchHistory() {
    const searchHistory = wx.getStorageSync('searchHistory') || []
    this.setData({ searchHistory })
  },

  // 搜索输入处理（实时搜索）
  onSearchInput(e) {
    const searchValue = e.detail.value
    this.setData({ 
      searchValue,
      showSearchResult: searchValue.trim().length > 0
    })
    
    // 防抖处理，200ms后执行搜索
    if (this.data.searchDebounceTimer) {
      clearTimeout(this.data.searchDebounceTimer)
    }
    
    const timer = setTimeout(() => {
      this.performRealTimeSearch(searchValue)
    }, 200)
    
    this.setData({ searchDebounceTimer: timer })
  },

  // 执行实时搜索
  performRealTimeSearch(searchValue) {
    if (!searchValue.trim()) {
      this.setData({
        filteredQuestions: this.data.questionList,
        showSearchResult: false
      })
      return
    }

    this.setData({ isSearching: true })
    
    // 模拟网络请求延迟
    setTimeout(() => {
      this.filterQuestions(searchValue)
      this.setData({ isSearching: false })
    }, 100)
  },

  // 搜索按钮点击（记录搜索历史）
  onSearchConfirm() {
    const { searchValue } = this.data
    if (!searchValue.trim()) return

    // 记录搜索历史
    this.addToSearchHistory(searchValue.trim())
    
    // 执行搜索
    this.performSearch(searchValue.trim())
  },

  // 执行正式搜索
  performSearch(keyword) {
    this.setData({ 
      isSearching: true,
      showSearchResult: true 
    })
    
    // 模拟网络请求
    setTimeout(() => {
      this.filterQuestions(keyword)
      this.setData({ isSearching: false })
      
      wx.showToast({
        title: `找到${this.data.filteredQuestions.length}个结果`,
        icon: 'none'
      })
    }, 300)
  },

  // 添加到搜索历史
  addToSearchHistory(keyword) {
    let searchHistory = wx.getStorageSync('searchHistory') || []
    
    // 移除重复项
    searchHistory = searchHistory.filter(item => item !== keyword)
    
    // 添加到开头
    searchHistory.unshift(keyword)
    
    // 只保留最近10条
    if (searchHistory.length > 10) {
      searchHistory = searchHistory.slice(0, 10)
    }
    
    wx.setStorageSync('searchHistory', searchHistory)
    this.setData({ searchHistory })
  },

  // 点击搜索历史
  onHistoryItemTap(e) {
    const keyword = e.currentTarget.dataset.keyword
    this.setData({ searchValue: keyword })
    this.performSearch(keyword)
  },

  // 点击热门搜索
  onHotSearchTap(e) {
    const keyword = e.currentTarget.dataset.keyword
    this.setData({ searchValue: keyword })
    this.performSearch(keyword)
  },

  // 清空搜索历史
  clearSearchHistory() {
    wx.showModal({
      title: '确认清空',
      content: '确定要清空搜索历史吗？',
      success: (res) => {
        if (res.confirm) {
          wx.removeStorageSync('searchHistory')
          this.setData({ searchHistory: [] })
          wx.showToast({
            title: '已清空',
            icon: 'success'
          })
        }
      }
    })
  },

  // 取消搜索
  onSearchCancel() {
    this.setData({
      searchValue: '',
      showSearchResult: false,
      filteredQuestions: this.data.questionList
    })
  },

  // 筛选题目
  filterQuestions(searchValue = null) {
    const { questionList, selectedCategory } = this.data
    const keyword = searchValue || this.data.searchValue
    let filtered = [...questionList]

    // 按分类筛选
    if (selectedCategory !== '全部') {
      filtered = filtered.filter(item => item.category === selectedCategory)
    }

    // 按搜索关键词筛选
    if (keyword.trim()) {
      filtered = filtered.filter(item => 
        item.name.toLowerCase().includes(keyword.toLowerCase()) ||
        item.description.toLowerCase().includes(keyword.toLowerCase()) ||
        item.tags?.some(tag => tag.toLowerCase().includes(keyword.toLowerCase()))
      )
    }

    this.setData({
      filteredQuestions: filtered
    })
  },

  // 分类选择
  onCategorySelect(e) {
    const category = e.currentTarget.dataset.category
    this.setData({ selectedCategory: category })
    this.filterQuestions()
  },

  // 跳转到题库详情
  goToBankDetail(e) {
    const bankId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/bank-detail/bank-detail?id=${bankId}`
    })
  },

  // 搜索框获得焦点
  onSearchFocus() {
    if (!this.data.searchValue.trim()) {
      this.setData({ showSearchResult: false })
    }
  },

  // 搜索框失去焦点
  onSearchBlur() {
    // 延迟隐藏，避免点击搜索建议时立即隐藏
    setTimeout(() => {
      if (!this.data.searchValue.trim()) {
        this.setData({ showSearchResult: false })
      }
    }, 200)
  },

  // 分享
  onShareAppMessage() {
    return {
      title: '题库小程序 - 海量题目等你来挑战！',
      path: '/pages/question-bank/question-bank'
    }
  }
})